package com.lenovo.spider.component.interceptor;

import com.lenovo.spider.Context;
import com.lenovo.spider.common.spi.ServiceProvider;
import com.lenovo.spider.component.ProxyPool;
import com.lenovo.spider.component.TaskProcess.PreDownloaderInterceptor;
import com.lenovo.spider.domain.Task;
import lombok.val;

/**
 * 代理切换
 *
 * @author <a href="mailto:liuhan3@lenovo.com">HanL(liuhan3)</a>
 * on 2018/4/13 16:31
 */
@ServiceProvider
public class ProxyChanger implements PreDownloaderInterceptor {

    final ProxyPool proxyPool;

    public ProxyChanger() {
        this.proxyPool = Context.getProxyPool();
    }

    @Override
    public boolean support(Task task) {
        return task.isSuccess();
    }

    @Override
    public Task handle(Task task) throws Exception {
        val req = task.getRequest();
        val proxy = req.getProxy();
        if (proxy == null || req.isChangeProxy()) {
            // 不存在代理配置或者需要切换代理
            req.setProxy(proxyPool.getProxy(task, req.isChangeProxy()));
            // 归还旧的代理
            proxyPool.returnProxy(task, proxy);
        }
        return task;
    }
}
